/**
* @description: 会商预演-会商执行/推演执行
* @author: zhaohui & yanxiaoyue
* @data:2023年6月20日 2023年7月17日
* @remark:
**/
<template>
	<view class="app-container">
		<nav-bar class="header" back :title="title" @goBack="goBack" />
		<view class="app-content">
			<view class="content">
				<view class="content-title">
					{{ setpsTitle }}
				</view>
				<view class="content-steps">
					<setps-consult-view :setpList="setpList" :active="setpsActive" @operate="stepsClick"
						:flowState="initDataParam.flowState">
					</setps-consult-view>
				</view>
				<view class="content-title">
					会议纪要
				</view>
				<view class="content-img">
					<view class="signintitle">
						<view class="content-img-title">现场照片:（最多上传3张）</view>
						<view class="image-wrap">
							<view class="image-list">
								<view class="upload-button" v-for="(imgItem, index) in files" :key="index">
									<view v-if="imgItem.img && initDataParam.flowState !== '2'" class="delete-icon"
										@click.stop="imageHandle(index,imgItem, 'DELETE')">
										×
									</view>
									<img v-if="imgItem.img" :src="imgItem.img" alt=""
										@click.stop="imageHandle(index,imgItem, 'PREVIEW')">
								</view>
								<img class="upload-button"
									v-if="files.length < wxCount && initDataParam.flowState !=='2'"
									src="../../../../static/img/ywgj.png" alt=""
									@click.stop="imageHandle(0,null, 'CHOOSE')">
							</view>

						</view>
					</view>

					<view>
						<view class="content-img-title">情况说明</view>
						<textarea class="content-description" v-model="situationDescription" :disabled="isDisabled"
							placeholder="请输入情况说明" />
					</view>
				</view>
			</view>
			<!-- ！==2就是未完成的有按钮，===“2”不出来，无按钮  -->
			<view class="sub-btn-container" v-if="initDataParam.flowState !=='2'">
				<van-button class="submit-btn" block type="info" color="#417ADC" @click="subClick">提交
				</van-button>
			</view>
		</view>
		<van-popup class="van-preview-wrap" v-model="showPreview" @click="showPreview = false">
			<van-swipe>
				<div v-for="(image, index) in fileList" :key="index">
					<van-swipe-item v-if="image.img" style="text-align: center;">
						<img :src="image.img" />
					</van-swipe-item>
				</div>
			</van-swipe>
		</van-popup>
	</view>
</template>

<script>
	import navBar from '../../common/navBar'
	import setpsConsultView from '../../common/stepsConsultView.vue'
	import axios from 'axios'
	import {
		Dialog,
		Toast
	} from "vant"
	import {
		insertexecute
	} from "../../../../api/bzhzyApi"
	import wx from '../../../../static/common_js/jweixin_1.0.0'
	import baseConfig from "../../../../common/config";
	let config = {}
	baseConfig.getOptions.then(res => {
		config = res
	})
	export default {
		name: "negotiateExceution",
		components: {
			navBar,
			setpsConsultView
		},
		data() {
			return {
				baseUrl: "",
				isRefresh: false,
				title: "",
				setpsTitle: "",
				situationDescription: "",
				initDataParam: {},
				setpList: [], //小节点数据
				setpsActive: "0", //节点进度
				files: [],
				pushParam: null, //跳转传参
				isDisabled: false,
				showPreview: false, //图片预览
				fileList: [], //图片预览数据
				wxCount: 3, //相册可选取数量，默认3张
				base64List: [], //相册文件数据

			};
		},
		onLoad(option) {
			this.initDataParam = JSON.parse(decodeURIComponent(option.message));
			this.baseUrl = config.firstUrl
			// this.baseUrl = `http://${this.$apiRequest.bzhzyApi.fileUrl}`
		},
		onShow() {
			this.initData()
		},
		methods: {
			goBack() {
				uni.navigateBack()
			},
			/**
			 * 通知上一个页面刷新数据
			 */
			back() {
				let pages = getCurrentPages();
				let prevPage = pages[pages.length - 2]; //上一个页面
				prevPage.isRefresh = true
				uni.navigateBack()
			},
			/**
			 * flowState === 2已完成-查看
			 */
			initData() {
				if (this.initDataParam.flowName === "会商执行") {
					this.title = "会商执行"
					this.setpsTitle = "会商内容"
				} else {
					this.title = "推演执行"
					this.setpsTitle = "推演内容"
				}
				this.$apiRequest.bzhzyApi.selecthsexecute({
					workPlanId: this.initDataParam.id,
					consultationDeductionId: this.initDataParam.objId
				}).then(res => {
					this.setpList = res.data.selectflowContentLogs
					console.log(this.initDataParam.flowState === '2')
					if (this.initDataParam.flowState === '2') {
						this.isDisabled = true
						this.situationDescription = res.data.selectallocation ? res.data.selectallocation
							.consultationDescription : ""

						if (res.data.selectfilemanage.length === 0) {
							this.files = []
						} else {
							this.files = res.data.selectfilemanage.filter(item => {
								item.img = this.baseUrl + item.filePath
								return item
							})
						}
					}
				}).catch(error => {

				})
			},
			/**
			 * @param {Object} data
			 *
			 * buttonState 按钮状态 （0：未完成 、1：已完成）
			 * pageFlag  区分是会商1/检修准备0
			 * tag区分是查看还是编辑
			 */
			stepsClick(data, text) {
				let pushParam = {
					id: data.workPlanId,
					OBJID: data.consultationDeductionId,
					pageFlag: '1',
				}
				let message = {
					id: data.workPlanId,
					OBJID: data.consultationDeductionId,
					flowId: data.tFlowContentId,
					pageFlag: '1',
				}
				if (data.flowName === "作业信息" && data.buttonState === 0) {
					// 作业信息填写
					uni.navigateTo({
						url: '/pages/standardizedOperation/meetPreview/jobInfoFilling?message=' +
							encodeURIComponent(JSON.stringify(message))
					})
				} else if (data.flowName === "作业信息" && data.buttonState === 1) {
					if (text === '编辑') {
						// 作业信息编辑
						uni.navigateTo({
							url: '/pages/standardizedOperation/meetPreview/jobInfoFilling?message=' +
								encodeURIComponent(JSON.stringify(message))
						})
					} else if (text === '查看') {
						// 作业信息查看
						uni.navigateTo({
							url: '/pages/standardizedOperation/meetPreview/jobInfoDetails?pushParam=' +
								encodeURIComponent(JSON.stringify(pushParam))
						})
					}
				} else if (data.flowName === "作业项目" && data.buttonState === 0) {
					// 作业项目确认
					uni.navigateTo({
						url: '/pages/standardizedOperation/jobItem/jobItem?message=' + encodeURIComponent(JSON
							.stringify(message))
					})
				} else if (data.flowName === "作业项目" && data.buttonState === 1) {
					if (text === '编辑') {
						// 作业项目编辑
						uni.navigateTo({
							url: '/pages/standardizedOperation/jobItem/jobItem?message=' + encodeURIComponent(JSON
								.stringify(message))
						})
					} else if (text === '查看') {
						// 作业项目查看
						uni.navigateTo({
							url: '/pages/standardizedOperation/jobItem/jobItemDetails?pushParam=' +
								encodeURIComponent(JSON.stringify(pushParam))
						})
					}
				} else if (data.flowName === "危险点分析及预控措施" && data.buttonState === 0) {
					// 危险点分析及预控措施确认
					uni.navigateTo({
						url: '/pages/standardizedOperation/fieldImplementation/dangerDetails/danger?message=' +
							encodeURIComponent(JSON.stringify(message))
					})
				} else if (data.flowName === "危险点分析及预控措施" && data.buttonState === 1) {
					if (text === '编辑') {
						// 危险点分析及预控措施编辑
						uni.navigateTo({
							url: '/pages/standardizedOperation/fieldImplementation/dangerDetails/danger?message=' +
								encodeURIComponent(JSON.stringify(message))
						})
					} else if (text === '查看') {
						// 危险点分析及预控措施查看
						uni.navigateTo({
							url: '/pages/standardizedOperation/fieldImplementation/dangerDetails/dangerDetails?pushParam=' +
								encodeURIComponent(JSON.stringify(pushParam))
						})
					}

				} else if (data.flowName === "检修备件" && data.buttonState === 0) {
					// 检修备确认
					uni.navigateTo({
						url: '/pages/standardizedOperation/MaintenanceSpare/index?message=' + encodeURIComponent(
							JSON.stringify(message))
					})
				} else if (data.flowName === "检修备件" && data.buttonState === 1) {
					if (text === '编辑') {
						// 检修备件确认
						uni.navigateTo({
							url: '/pages/standardizedOperation/MaintenanceSpare/index?message=' +
								encodeURIComponent(JSON.stringify(message))
						})
					} else if (text === '查看') {
						// 检修备件查看
						uni.navigateTo({
							url: '/pages/standardizedOperation/MaintenanceSpare/details?pushParam=' +
								encodeURIComponent(JSON.stringify(pushParam))
						})
					}
				}
			},
			/**
			 * buttonStateList 作业内容是否全部完成记录
			 */
			subClick() {
				let isFile = false
				let buttonStateList = []
				this.setpList.forEach(item => {
					if (item.buttonState === 1) {
						buttonStateList.push(item.buttonState)
					}
				})
				this.files.forEach(item => {
					if (item.raw) {
						isFile = true
					}
				})
				if (buttonStateList.length !== this.setpList.length) {
					Toast("作业内容流程未执行完成")
					return
				}
				if (!isFile) {
					Toast("请拍摄照片")
					return
				}
				if (!this.situationDescription) {
					Toast("请输入情况说明")
					return
				}
				Dialog.confirm({
						message: '提交后不可修改，是否确定提交？',
						confirmButtonColor: "#417adc"
					})
					.then(() => {
						Toast.loading({
							duration: 0,
							message: '加载中...',
							forbidClick: true
						})
						let formData = new FormData()
						if (this.files.length > 0) {
							this.files.forEach((item, index) => {
								if (item.raw) {
									formData.append("files", item.raw)
								}
							})
						}
						formData.append("workPlanId", this.initDataParam.id) //计划id
						formData.append("consultationDeductionId", this.initDataParam.objId) //施工流程节点id
						formData.append("consultationDescription", this.situationDescription) //情况说明
						let config = {
							headers: {
								'Content-Type': 'multipart/form-data',
								Authorization: uni.getStorageSync('token') || ''
							}
						}
						let url = ''
						// #ifndef IGW
						url = '/bzzy/web/api/consultationdeduction/insertexecute'
						// #endif
						// #ifdef IGW
						url = `${this.baseUrl}/bzzy/web/api/consultationdeduction/insertexecute`
						// #endif
						
						// url =
						// 	`http://${this.$apiRequest.bzhzyApi.fileUrl}/bzzy/web/api/consultationdeduction/insertexecute`
						
						
						axios.post(url, formData, config).then(res => {
							Toast.clear()
							Toast(res.data.msg)
							if (res.data.code == 0) {
								this.back();
							}
						}).catch(error => {
							Toast.clear()
							Toast('提交失败')
						})
					})
					.catch(() => {
						// on cancel
					});
			},
			imageHandle(imgIndex, imgItem, handleType) {
				if (handleType === 'CHOOSE' && this.initDataParam.flowState !== '2') {
					// let base64List = []
					// let base64File =
					// 	""
					// let fileRaw = this.dataURLtoFile(base64File, "test.jpeg")
					// base64List.push({
					// 	raw: fileRaw,
					// 	img: base64File,
					// })
					// base64List.forEach(img => {
					// 	this.files.push(img)
					// })
					this.choosePhoto()
				} else if (handleType === 'PREVIEW') {
					this.fileList = [imgItem]
					this.showPreview = true
				} else if (handleType === 'DELETE' && this.initDataParam.flowState !== '2') {
					this.files.splice(imgIndex, 1)
				}
			},
			choosePhoto() {
				let _this = this
				//相册可选的数量
				let num = 0
				this.files.forEach(item => {
					if (item.img && item.raw) {
						num++
					}
				})
				let selectNum = this.wxCount - num
				wx.chooseImage({
					count: selectNum,
					sourceType: ['album', 'camera'],
					success: chooseImageRes => {
						Toast.loading({
							duration: 0,
							message: '加载中...',
							forbidClick: true
						})
						_this.syncLocalImg(chooseImageRes.localIds)
					},
					fail: error => {
						console.log(error)
					}
				})
			},
			async syncLocalImg(localIds) {
				this.base64List = []
				for (let i = 0; i < localIds.length; i++) {
					await this.syncUpload(localIds[i], i, localIds.length)
				}
			},
			syncUpload(localId, i, localIdsLength) {
				let self = this;
				return new Promise(resolve => {
					wx.getLocalImgData({
						localId, // 图片的localID
						success: function(resBackData) {
							let localData = resBackData.localData;
							let imageBase64 = ''
							const photoName = `${new Date().getTime()}`
							//判断是否有这样的头部
							if (localData.indexOf('data:image') == 0) {
								//苹果的直接赋值，默认生成'data:image/jpeg;base64,'的头部拼接
								imageBase64 = localData
							} else {
								//此处是安卓中的唯一得坑！在拼接前需要对localData进行换行符的全局替换
								//此时一个正常的base64图片路径就完美生成赋值到img的src中了
								imageBase64 =
									'data:image/jpeg;base64,' + localData.replace(/\n/g, '')
							}
							//直接使用imageBase64展示，会导致swipe卡顿
							let file = self.dataURLtoFile(imageBase64,
								`${photoName}.jpeg`)
							let blob = self.h5_url_to_blob(imageBase64)
							self.base64List.push({
								raw: file,
								img: URL.createObjectURL(blob),
							})
							if (i + 1 === localIdsLength) {
								Toast.clear()
								self.base64List.forEach(img => {
									self.files.push(img)
								})
							}
							resolve("ok")
						},
					})
				})
			},
			dataURLtoFile(dataurl, filename) {
				var arr = dataurl.split(','),
					mime = arr[0].match(/:(.*?);/)[1],
					bstr = atob(arr[1]),
					n = bstr.length,
					u8arr = new Uint8Array(n)
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n)
				}
				return new File([u8arr], filename, {
					type: mime
				})
			},
			h5_url_to_blob(url) {
				let arr = url.split(',')
				let mime = arr[0].match(/:(.*?);/)[1]
				let bstr = atob(arr[1])
				let n = bstr.length
				let u8arr = new Uint8Array(n)
				while (n--) {
					u8arr[n] = bstr.charCodeAt(n)
				}
				return new Blob([u8arr], {
					type: mime
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.app-container {
		display: flex;
		flex-direction: column;
		width: 100vw;
		height: 100vh;
		box-sizing: border-box;
		background-color: #f2f6fa;

		.app-content {
			display: flex;
			flex-direction: column;
			flex: 1;
			overflow: hidden;
			box-sizing: border-box;

			.content {
				flex: 1;
				overflow-y: scroll;
				padding: 0 px2vh(30) px2vh(30) px2vh(30);
				box-sizing: border-box;

				.content-steps {
					background-color: #FFFFFF;
					border-radius: px2vh(20);
					padding: px2vh(30);
				}
			}

			.content-img-title {
				font-size: px2vh(40);
				color: #666666;
				line-height: px2vh(62);

				&::before {
					content: "*";
					color: red;
				}
			}

			.content-title {
				font-size: px2vw(40);
				font-weight: bold;
				line-height: px2vw(54);
				color: #666666;
				padding: px2vw(50) 0 px2vw(30) 0;
			}

			.content-img {
				width: 100%;
				background-color: #FFFFFF;
				padding: 0 px2vh(40) px2vh(50) px2vh(40);
				border-radius: px2vh(20);
				box-sizing: border-box;

				.signintitle {
					padding: px2vh(40) 0;
					box-sizing: border-box;
					display: flex;
					flex-direction: column;

					.pos {
						color: #417ADC;
					}

					.image-wrap {
						width: 100%;
						display: flex;

						.image-list {
							width: 100%;
							display: flex;

							img {
								width: px2vw(215);
								height: px2vw(215);
								margin-right: px2vw(40);
								border-radius: px2vw(6);
							}

							.upload-button {
								width: px2vw(215);
								height: px2vw(215);
								background-size: cover;
								margin-right: px2vw(40);
								position: relative;
								// background-image: url('../../../../static/img/ywgj.png');
								margin-top: px2vh(49);

								.delete-icon {
									position: absolute;
									top: px2vw(-20);
									right: px2vw(-20);
									width: px2vw(40);
									height: px2vw(40);
									background-color: #ff4355;
									border-radius: 50%;
									color: #fff;
									display: flex;
									justify-content: center;
									align-items: center;
								}
							}
						}

					}
				}

				.content-description {
					width: 100%;
					margin-top: px2vw(40);
					padding: px2vw(20);
					box-sizing: border-box;
					border-radius: px2vw(10);
					font-size: px2vh(38);
					color: #666666;
					line-height: px2vh(62);
					background-color: #F7F7F7;
					max-height: px2vw(280);
				}
			}

			.sub-btn-container {
				display: flex;
				align-items: center;
				justify-content: center;
				height: px2vw(200);

				.submit-btn {
					margin: 0 px2vw(30);
					border-radius: px2vw(20);
				}
			}
		}

		.van-preview-wrap {
			width: 100%;
			height: 100%;
			display: flex;
			align-items: center;

			.van-swipe {
				width: 100%;
				height: 100%;
			
				.van-swipe-item {
					display: flex;
			
					img {
						width: 100%;
						height: 100%;
						object-fit: contain;
					}
				}
			}
		}

		.van-popup {
			background-color: rgba(0, 0, 0, 0.8);

			.van-cell {
				position: absolute;
				bottom: 0;
				border-top: 4px solid #eee;
				z-index: 3;
			}
		}
	}
</style>
